package com.yorick.common.security;

import com.alibaba.fastjson.JSONObject;
import com.yorick.common.dao.SecurityMapper;
import com.yorick.common.util.IP;
import com.yorick.common.util.ResponseWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
public class IPWhiteListInterceptor implements HandlerInterceptor {
    @Resource
    SecurityMapper securityDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String remoteIP=IP.getIpAddr(request);
        List<String> ipWhiteList = securityDao.getIPWhiteList();
        if (StringUtils.isNotEmpty(remoteIP)){
            if (!ipWhiteList.contains(remoteIP)){
                JSONObject result = new JSONObject();
                result.put("flag", "-2");
                result.put("msg", "你的IP("+remoteIP+")不在白名单内，请联系管理员");
                ResponseWriter.responseOutWithJson(response, result);
                return false;
            }
        }
        return true;
    }
}
